package com.example.login.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private final String SMS_CODE_PREFIX = "sms:code:";

    public void setSmsCode(String phone, String code, long expireTime) {
        String key = SMS_CODE_PREFIX + phone;
        redisTemplate.opsForValue().set(key, code, expireTime, TimeUnit.SECONDS);
    }

    public String getSmsCode(String phone) {
        String key = SMS_CODE_PREFIX + phone;
        Object code = redisTemplate.opsForValue().get(key);
        return code != null ? code.toString() : null;
    }

    public boolean validateSmsCode(String phone, String code) {
        String savedCode = getSmsCode(phone);
        return savedCode != null && savedCode.equals(code);
    }

    public void deleteSmsCode(String phone) {
        String key = SMS_CODE_PREFIX + phone;
        redisTemplate.delete(key);
    }
}